<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '商户查询',
  },
}
</route>

<template>
  <view class="container">
    <view class="sticky">
      <wd-search
        v-model="searchText"
        cancel-txt="搜索"
        placeholder="输入商户名称搜索"
        @search="onSearch"
        @clear="onClear"
      >
        <template #suffix>
          <view class="filter-trigger">
            <wd-icon name="filter1" size="20px" color="#4d80f0" class="filter-icon" @click="filterVisible = true" />
          </view>
        </template>
      </wd-search>
      <!-- <view class="date-filter">
        <wd-datetime-picker type="date" v-model="startDate" placeholder="开始日期" />
        <wd-datetime-picker type="date" v-model="endDate" placeholder="结束日期" />
        <wd-button size="small" type="primary" @click="applyDateFilter">筛选</wd-button>
      </view> -->
    </view>

    <wd-popup v-model="filterVisible" position="right">
      <view class="filter-panel">
        <view class="filter-title">筛选</view>
        <wd-calendar type="daterange" v-model="calendarRange" @confirm="onCalendarConfirm" />
        <view class="filter-actions">
          <wd-button size="small" plain @click="resetCalendar">重置</wd-button>
          <wd-button size="small" type="primary" @click="applyAndClose">应用</wd-button>
        </view>
      </view>
    </wd-popup>

    <view class="list-wrapper">
      <view v-if="renderList.length === 0 && state !== 'loading'" class="empty">
        <uni-icons type="list" size="36" color="#cccccc" />
        <text class="empty-text">暂无数据</text>
      </view>

      <view v-for="item in renderList" :key="item.userId" class="merchant-card" @click="goMerchantOrders(item)">
        <view class="row header">
          <view class="title-line">
            <image
              class="avatar-sm"
              :src="item.avatarUrl || '/static/app/icons/96x96.png'"
              mode="aspectFill"
            />
            <text class="title">{{ item.nickName || '-' }}</text>
          </view>
          <wd-tag type="success" shape="fillet">￥{{ (item.totalAmount || 0) / 100 }}</wd-tag>
        </view>

        <view class="row info">
          <text class="label">电话</text>
          <text class="value">{{ item.phone || '-' }}</text>
        </view>

        <view class="row info">
          <text class="label">订单数</text>
          <text class="value">{{ item.total || 0 }}</text>
        </view>

        <view class="row info">
          <text class="label">已支付金额</text>
          <text class="value price">￥{{ (item.totalAmount || 0) / 100 }}</text>
        </view>

        <view class="row info">
          <text class="label">退款单数</text>
          <text class="value">{{ item.refundCount || 0 }}</text>
        </view>

        <view class="row info">
          <text class="label">退款金额</text>
          <text class="value price">￥{{ (item.refundAmount || 0) / 100 }}</text>
        </view>
      </view>
    </view>

    <wd-loadmore :state="state" @reload="reload" />
  </view>
</template>

<script lang="ts" setup>
import { httpPost } from '@/utils/http'
import { onLoad } from '@dcloudio/uni-app'
import dayjs from 'dayjs'

const list = ref<any[]>([])
const state = ref<any>('loading')
const startDate = ref<number>(0)
const endDate = ref<number>(0)
const filterVisible = ref<boolean>(false)
const calendarRange = ref<any>('')

const getList = async () => {
  const body: any = {}
  if (startDate.value) {
    body.createTime = dayjs(startDate.value).startOf('day').format('YYYY-MM-DD HH:mm:ss')
  }
  if (endDate.value) {
    body.endTime = dayjs(endDate.value).endOf('day').format('YYYY-MM-DD HH:mm:ss')
  }
  const _res: any = await httpPost('/api/app/order/order/merchantSummary', body)
  list.value = _res || []
  state.value = 'finished'
}

onLoad(() => {
  getList()
})

function reload() {
  state.value = 'loading'
  list.value = []
  getList()
}

function applyAndClose() {
  if (Array.isArray(calendarRange.value) && calendarRange.value.length === 2) {
    startDate.value = Number(calendarRange.value[0])
    endDate.value = Number(calendarRange.value[1])
  }
  applyDateFilter()
  filterVisible.value = false
}

function onCalendarConfirm({ value }: any) {
  if (Array.isArray(value) && value.length === 2) {
    startDate.value = Number(value[0])
    endDate.value = Number(value[1])
  }
}

function resetCalendar() {
  calendarRange.value = ''
  startDate.value = 0
  endDate.value = 0
}

const searchText = ref<string>('')
const renderList = computed(() => {
  const keyword = (searchText.value || '').trim()
  let arr = list.value || []
  if (!keyword) return arr
  return arr.filter((e: any) => String(e.nickName || '').includes(keyword))
})

function onSearch() {}
function onClear() {
  searchText.value = ''
}
function applyDateFilter() {
  list.value = []
  state.value = 'loading'
  getList()
}

function goMerchantOrders(item: any) {
  const qs: string[] = []
  if (startDate.value) {
    qs.push('createTime=' + encodeURIComponent(dayjs(startDate.value).startOf('day').format('YYYY-MM-DD HH:mm:ss')))
  }
  if (endDate.value) {
    qs.push('endTime=' + encodeURIComponent(dayjs(endDate.value).endOf('day').format('YYYY-MM-DD HH:mm:ss')))
  }
  qs.push('deviceBindUserId=' + item.userId)
  const url = '/pages/index/order/index' + (qs.length ? ('?' + qs.join('&')) : '')
  uni.navigateTo({ url })
}
</script>

<style lang="scss" scoped>
.sticky {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #f7f7f7;
  padding: 20rpx 24rpx;
}
.filter-trigger {
  display: flex;
  justify-content: flex-end;
  margin-top: 8rpx;
}
.filter-icon {
  padding: 8rpx;
}
.filter-panel {
  width: 86vw;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
}
.filter-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 16rpx;
}
.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12rpx;
  margin-top: 16rpx;
}
.date-filter {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-top: 16rpx;
}
.list-wrapper {
  padding: 24rpx;
}
.merchant-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 28rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header {
  margin-bottom: 16rpx;
}
.title-line {
  display: flex;
  align-items: center;
  gap: 12rpx;
}
.avatar-sm {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
}
.title {
  font-size: 30rpx;
  color: #333;
}
.info {
  margin: 10rpx 0;
}
.label {
  color: #666;
  font-size: 26rpx;
}
.value {
  color: #333;
  font-size: 28rpx;
}
.price {
  color: #e60012;
  font-weight: 600;
}
.empty {
  padding: 60rpx 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
}
.empty-text {
  color: #999;
  font-size: 28rpx;
}
</style>
